<?php

namespace app\admin\controller\mall\oper;

use app\admin\controller\mall\Base;
use fast\Tree;
use think\Cache;

/**
 * 地区
 *
 * @icon fa fa-circle-o
 */
class Area extends Base
{
    
    /**
     * Area模型对象
     * @var \app\common\model\mall\oper\Area
     */
    protected $model = null;
    protected $arealist = [];
    protected $multiFields = 'ismenu,status';
    
    public function _initialize()
    {
        parent::_initialize();
        $exist = \think\Db::query("show tables like'".config('database.prefix')."area'");
        if(!$exist) $this->error("地区数据不存在，请安装<a href=\"https://www.fastadmin.net/store/example.html\" target=\"_blank\">[开发示例]</a>插件！");

        $this->model = new \app\common\model\mall\oper\Area;
        $this->view->assign("levelList", $this->model->getLevelList());
        //数据量大，此处需要设置超时执行
        set_time_limit(0);

        $this->arealist = $this->model->getTreeList();
        //生成父节点数据，用于编辑表单选择器
        $areadata = [0 => __('None')];
        foreach ($this->arealist as &$v)
        {
            if ($v['level'] == $this->model->max('level')) continue;
            $areadata[$v['id']] = $v['name'];
        }
        //恢复限时执行30秒
        set_time_limit(30);
        $this->view->assign('areadata', $areadata);
    }
    
    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax())
        {
            $id = $this->request->param("id/d",0);

            $list = $this->model->getChild($id);

            $result = array("total" => count($list), "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids)
        {
            $delIds = [];
            $idsArr = explode(",", $ids);
            $delIds = $this->model->getChildIds($idsArr,$idsArr);
            $delIds = array_unique($delIds);
            $count = $this->model->where('id', 'in', $delIds)->delete();
            if ($count)
            {
                $this->success();
            }
        }
        $this->error();
    }

    /**
     * Selectpage搜索
     *
     * @internal
     */
    public function selectpage()
    {
        return parent::selectpage();
    }
}
